package org.kfive.nova.thread;

import java.util.concurrent.*;

/**
 * Created by admin on 2017-04-14.
 */
public class CompletionServiceThread {
    public static class Task implements Callable<Integer>{

        private int i;

        public Task(int i){
            this.i=i;
        }
        @Override
        public Integer call() throws Exception {
            Thread.sleep(10000);
            System.out.println(Thread.currentThread().getName() + "   " + i);
            return i;
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService);
        try {
            for (int i=1;i<=10;i++){
                completionService.submit(new Task(i));
            }
            for (int i=1;i<=10;i++){
                System.out.println(completionService.take().get());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

}
